<?php
/**
 * 自动创建create_time和update_time字段
 * Enter description here ...
 * @author nijn
 *
 */
class CreateTimeBehavior extends CActiveRecordBehavior{

	public function afterConstruct($event) {
		$owner = $this->owner;
		$db = Yii::app()->db;
		$tableName = $owner->tableName();
		$sql = "ALTER TABLE `{$tableName}` ";
		$addSql = '';
		$attribute = array();
		foreach (array('create_time','update_time') as $one) {
			$timeSql = "select COUNT(*) from information_schema.columns where TABLE_NAME='{$tableName}' and COLUMN_NAME='{$one}'";
			$result = $db->createCommand($timeSql)->queryColumn();
			$attribute[$one] = $result[0];
		}
		if ($attribute['create_time'] == 0) {
			$addSql .= 'ADD create_time datetime';
		}
		if($attribute['update_time'] == 0) {
			$addSql .= empty($addSql) ? 'ADD update_time datetime' : ',ADD update_time datetime';
		}
		if (!empty($addSql))
			$db->createCommand($sql.$addSql)->query();
	}
}

?>